import { loadEsriModule } from '@/utils/jsapi'
import env from '@/utils/env'
import store from '@/vuex/store'
import Axios from 'axios'
import { is } from 'core-js/fn/object'
const aliasLevels = ['无', '低', '较低', '中', '较高', '高']

// 几环内有哪些乡镇
const huanXZ = {
  2: ['110101002000', '110101014000', '110101001000', '110102011000', '110101013000', '110102017000', '110101004000', '110102018000', '110101008000', '110102001000', '110101005000', '110101006000', '110102014000', '110102012000', '110102015000', '110102003000', '110101003000', '110101007000', '110101012000', '110101011000', '110102019000', '110102013000', '110101016000', '110101015000', '110102016000'],
  3: ['110102010000', '110105003000', '110106013000', '110102020000', '110101002000', '110101014000', '110105028000', '110101010000', '110101001000', '110102011000', '110105005000', '110102009000', '110101013000', '110102017000', '110108007000', '110108008000', '110106018000', '110101004000', '110102018000', '110101008000', '110102001000', '110105018000', '110101005000', '110108006000', '110102007000', '110106002000', '110105007000', '110101006000', '110102014000', '110102012000', '110106003000', '110106001000', '110108004000', '110105001000', '110102015000', '110105006000', '110102003000', '110101003000', '110105008000', '110105016000', '110106007000', '110101007000', '110101012000', '110105002000', '110102019000', '110101011000', '110101009000', '110102013000', '110101017000', '110108003000', '110101016000', '110101015000', '110105004000', '110102016000', '110105017000'],
  4: ['110102010000', '110105022000', '110105027000', '110108011000', '110105003000', '110105014000', '110106013000', '110102020000', '110105028000', '110101014000', '110101002000', '110101010000', '110101001000', '110102011000', '110106009000', '110105005000', '110105009000', '110102009000', '110105012000', '110108001000', '110101013000', '110102017000', '110108007000', '110108008000', '110106018000', '110101004000', '110102018000', '110101008000', '110102001000', '110105018000', '110101005000', '110108006000', '110102007000', '110106002000', '110105007000', '110105026000', '110101006000', '110105006000', '110105030000', '110102014000', '110105015000', '110102012000', '110106003000', '110106001000', '110108025000', '110108004000', '110105021000', '110102015000', '110108018000', '110102003000', '110105001000', '110101003000', '110105008000', '110105016000', '110106007000', '110105013000', '110105010000', '110101007000', '110106004000', '110101012000', '110105002000', '110102019000', '110105023000', '110101011000', '110101009000', '110102013000', '110101017000', '110108003000', '110101016000', '110106008000', '110101015000', '110105024000', '110102016000', '110105004000', '110105017000', '110106015000', '110108005000', '110108012000'],
  5: ['110105014000', '110105012000', '110101004000', '110102001000', '110106006000', '110108006000', '110108023000', '110105007000', '110108021000', '110105001000', '110106001000', '110108004000', '110105006000', '110102003000', '110105008000', '110105010000', '110105043000', '110108014000', '110105042000', '110107002000', '110105024000', '110102016000', '110102010000', '110115005000', '110115007000', '110105003000', '110106013000', '110102020000', '110107001000', '110101010000', '110106009000', '110108001000', '110102017000', '110108007000', '110101008000', '110108010000', '110115006000', '110106002000', '110101006000', '110105030000', '110105039000', '110108025000', '110105021000', '110105031000', '110105011000', '110108018000', '110105025000', '110105023000', '110101009000', '110105038000', '110106008000', '110108012000', '110106014000', '110105019000', '110105027000', '110105028000', '110101014000', '110108017000', '110105009000', '110108027000', '110101013000', '110106018000', '110105018000', '110101005000', '110106016000', '110108013000', '110102014000', '110106003000', '110101007000', '110101012000', '110105002000', '110108015000', '110102013000', '110101017000', '110101016000', '110101015000', '110108002000', '110105004000', '110107005000', '110105017000', '110105022000', '110108011000', '110105029000', '110101002000', '110101001000', '110102011000', '110105005000', '110106005000', '110102009000', '110107003000', '110108008000', '110102018000', '110105041000', '110102007000', '110105026000', '110108024000', '110102012000', '110105015000', '110115004000', '110102015000', '110101003000', '110105016000', '110106007000', '110105013000', '110105032000', '110106004000', '110102019000', '110101011000', '110107011000', '110108003000', '110106015000', '110108005000']
}

const huanQu = {
  2: ['110102', '110101'],
  3: ['110108', '110105', '110102', '110101', '110106'],
  4: ['110108', '110102', '110105', '110101', '110106'],
  5: ['110108', '110101', '110107', '110106', '110102', '110105', '110115'],
  9: ['110119', '110105', '110115', '110109', '110113', '110112', '110101', '110116', '110102', '110114', '110106', '110117', '110118', '110111', '110108', '110107']
}

var mapSelectOption = {
  spatialUnit: 0, // 空间单元，区县为0，乡镇为1
  huanLevel: 0 // 环路等级：0 全市 2 二环 3 三环 4 四环 5 五环 9 区县;
}

function contains (arr, obj) {
  let i = arr.length
  while (i--) {
    if (arr[i] === obj) {
      return true
    }
  }
  return false
}

function getRandomColor () {
  var r = Math.round(Math.random() * 255); var g = Math.round(Math.random() * 255); var b = Math.round(Math.random() * 255)
  var color = r << 16 | g << 8 | b
  return '#' + color.toString(16)
}

function getRenderValByRegionCode (renderData, regioncode) {
  let huanArr
  let huanCondition = mapSelectOption.spatialUnit == 0 ? huanQu : huanXZ
  if (mapSelectOption.huanLevel > 0 && mapSelectOption.huanLevel != 9) {
    // 当前乡镇且大于0时
    huanArr = huanCondition[mapSelectOption.huanLevel]
  }
  for (let i = 0; i < renderData.length; i++) {
    let item = renderData[i]
    if (mapSelectOption.huanLevel > 0 && mapSelectOption.huanLevel != 9) {
      // 条件用环路筛选
      if (huanArr && contains(huanArr, regioncode)) {
        if (item['regionCode'] == regioncode) {
          return item['nums'] // 在五环内
        }
      } else {
        return 'NAN' // 在五环外
      }
    } else if (mapSelectOption.huanLevel == 0) {
      if (item['regionCode'] == regioncode) { // 不做限制,全市
        return item['nums']
      }
    } else {
      if (item['regionCode'] == regioncode) { // 条件用区县筛选
        return item['nums']
      }
    }
  }
  return mapSelectOption.huanLevel == 9 ? 'NAN' : 0
}

/**
   * JS颜色十六进制转换为rgb或rgba,返回的格式为 rgba（255，255，255，0.5）字符串
   * sHex为传入的十六进制的色值
   * alpha为rgba的透明度
   */
function colorRgba (sHex, alpha = 0.5) {
  // 十六进制颜色值的正则表达式
  var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/
  /* 16进制颜色转为RGB格式 */
  let sColor = sHex.toLowerCase()
  if (sColor && reg.test(sColor)) {
    if (sColor.length === 4) {
      var sColorNew = '#'
      for (let i = 1; i < 4; i += 1) {
        sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1))
      }
      sColor = sColorNew
    }
    //  处理六位的颜色值
    var sColorChange = []
    for (let i = 1; i < 7; i += 2) {
      sColorChange.push(parseInt('0x' + sColor.slice(i, i + 2)))
    }
    sColorChange.push(alpha)
    // return sColorChange.join(',')
    // 或
    return sColorChange// 'rgba(' + sColorChange.join(',') + ',' + alpha + ')'
  } else {
    return sColor
  }
}

function Sort (mapData) {
  let values = mapData.map(function (val) {
    return Math.abs(val.value)
  })
  return values.sort((a, b) => a - b)
}

var qx_centers = { '110109': [451701.9547033111, 314235.9816696264],
  '110119': [483600.4944970751, 374664.65484878665],
  '110116': [519359.1610409224, 384565.3839543031],
  '110118': [554015.391780579, 373365.357249395],
  '110111': [456813.36773401103, 283667.0256480055],
  '110101': [505095.7005679591, 305047.4484575526],
  '110117': [567098.6534916459, 338208.6293643014],
  '110108': [489426.811103609, 317724.2464505397],
  '110113': [531168.362716971, 331429.19548793696],
  '110106': [490844.1418886481, 296487.72033711354],
  '110114': [487537.4657993636, 338652.3505158241],
  '110107': [484549.7534792036, 307333.983266414],
  '110102': [500735.4679898055, 304968.16583112837],
  '110105': [513396.30602028104, 309289.5557804322],
  '110112': [532231.1880156612, 292964.14832662285],
  '110115': [505299.2672350378, 275633.47843021195]
}
var xz_centers = { '110109106000': [443704.0361315475, 317568.798497651],
  '110119107000': [499767.83860511164, 392589.3399931907],
  '110109107000': [431333.8437923071, 309109.15952278365],
  '110116213000': [520253.2212553907, 418885.7522489352],
  '110114118000': [467886.2152727344, 333506.9017631339],
  '110109105000': [456739.0729700282, 322810.243280917],
  '110119105000': [458945.41566427174, 373188.31908033346],
  '110118116000': [536171.3181290871, 380657.6949053229],
  '110116211000': [532939.1638648591, 405059.6677044784],
  '110116111000': [511342.15032419, 402181.02517711953],
  '110118109000': [552829.6318852486, 381364.98429541383],
  '110116110000': [521418.70242950186, 380795.56655545544],
  '110116107000': [522605.149416468, 400019.39903896657],
  '110118107000': [566813.2882975229, 375747.7013693457],
  '110118110000': [544039.8081336773, 391730.7054120093],
  '110111208000': [443555.7764950152, 287830.48919590405],
  '110114002000': [476327.2642873624, 344174.4625340619],
  '110111111000': [434224.2027068764, 278450.55120959604],
  '110116109000': [502151.5714694503, 359277.4330151007],
  '110118115000': [586376.9530575732, 385125.87252508954],
  '110116004000': [520602.2763893972, 365323.2528167992],
  '110116108000': [510359.8693305633, 362489.80808804446],
  '110111210000': [457137.0898395883, 297140.53892020695],
  '110119103000': [487198.3531876145, 370767.7779224029],
  '110119203000': [509266.18177441426, 381658.13887316256],
  '110118112000': [567633.2144552062, 360788.7109639153],
  '110101013000': [506971.8116827311, 303333.9057536525],
  '110117006000': [581570.5325104096, 337478.4397374534],
  '110118102000': [534058.7120006861, 363233.08758066135],
  '110119110000': [478362.69068803376, 360116.35996033443],
  '110119200000': [488425.02280547854, 361288.1160469438],
  '110111110000': [445280.1559833493, 273319.4991407917],
  '110118106000': [551124.3671000105, 363103.81392419245],
  '110111009000': [460028.7771942049, 281144.5960300401],
  '110119202000': [484079.793731557, 384407.05262864963],
  '110118108000': [562702.4198168485, 384066.4529834046],
  '110119201000': [492603.7424125594, 379363.60861272103],
  '110119106000': [503734.10274966975, 373437.4209520157],
  '110112106000': [539682.3656766027, 286583.75950852584],
  '110109108000': [470937.8006412482, 317989.18045169965],
  '110118101000': [543171.4783524849, 367882.48363795027],
  '110118105000': [554493.7743979623, 356737.8313985561],
  '110118113000': [548990.0419372647, 347199.4914117723],
  '110111212000': [442594.67646321666, 297679.4800530019],
  '110109004000': [460046.8412088517, 309001.2596551822],
  '110117114000': [569865.9811518732, 352849.44498126255],
  '110109101000': [470152.94267052837, 302089.12638547324],
  '110119101000': [459477.6924896078, 360244.68807936396],
  '110111010000': [479288.2676988943, 270709.156565845],
  '110112104000': [530236.8876510418, 312135.6722807512],
  '110116105000': [514844.0393122258, 350021.0477005151],
  '110119104000': [474341.4009326306, 377457.4726521135],
  '110112110000': [543692.9468082088, 292876.4452930402],
  '110111109000': [451454.24416053237, 267431.2065206664],
  '110111213000': [427612.34457266086, 287453.5534887611],
  '110118111000': [570478.884119024, 388938.50439735706],
  '110108029000': [479730.6209445001, 323564.9375818874],
  '110112105000': [530487.855785907, 293810.36853150855],
  '110112117000': [537695.9087934132, 277532.17840824026],
  '110116106000': [527142.625604253, 366973.70036753116],
  '110111115000': [458631.3072977964, 274167.86710130627],
  '110119102000': [468396.2603351132, 353119.2466480095],
  '110117105000': [560014.6363731179, 347091.51028618304],
  '110113112000': [537061.9986788452, 341900.5181698389],
  '110113006000': [541204.4019985816, 330553.2294805675],
  '110118114000': [569486.5649005526, 369958.1947371792],
  '110111103000': [477563.22741487226, 275937.4178662942],
  '110117213000': [576238.7876533249, 344459.03116544214],
  '110101012000': [505307.9446572293, 303276.66610438784],
  '110111101000': [476148.85040956986, 282841.4397541016],
  '110117102000': [568513.4862327367, 337949.0374100202],
  '110114004000': [494164.7327203988, 329722.69078565855],
  '110114008000': [505616.6937915698, 322920.87761439173],
  '110113116000': [517084.4589205971, 338493.7232608319],
  '110113104000': [528734.4034080864, 320027.34497793554],
  '110112119000': [536044.1779979999, 300906.32597669115],
  '110117004000': [553983.7276502302, 335913.33579511876],
  '110117110000': [562392.4914442187, 337443.04245165654],
  '110116003000': [522582.36680779624, 353276.8261013607],
  '110111211000': [451190.91101186175, 302310.92820534215],
  '110114112000': [498657.0631842973, 341851.0100083888],
  '110105029000': [515635.88907689217, 307726.3015778379],
  '110113109000': [547809.607540213, 324268.73399033706],
  '110118104000': [539949.0793019739, 350256.3507637756],
  '110114110000': [505450.71790994104, 333017.7680569967],
  '110111107000': [465596.6268655422, 295071.76971167815],
  '110117104000': [573783.7745864998, 335845.3629688991],
  '110116102000': [530572.9319202135, 351186.439836703],
  '110108026000': [484737.1178236543, 319337.17664761667],
  '110111104000': [469077.2174120306, 275061.81082597456],
  '110108027000': [489856.38354579377, 310565.90636460617],
  '110105036000': [520720.2849469494, 313048.0771910447],
  '110108028000': [490477.29092218244, 321702.98209116317],
  '110106011000': [484426.6606768877, 297745.53699430695],
  '110117214000': [568477.3688005012, 346520.09049612633],
  '110113111000': [543937.3626879527, 340949.628140047],
  '110114010000': [500824.94878057024, 323605.27540898474],
  '110111108000': [457950.6904612615, 268724.45642971474],
  '110105026000': [509371.0741056674, 313459.0765799417],
  '110114111000': [494432.3179510478, 338639.2329195266],
  '110105033000': [520893.42272040824, 306947.8535498752],
  '110113113000': [531551.9225924436, 337905.00789128285],
  '110114115000': [506052.1572146989, 326913.0658434785],
  '110106101000': [479875.9509049621, 293859.9086446381],
  '110117101000': [563170.5048116843, 324794.56954741],
  '110111008000': [482664.8929914221, 280359.0166849839],
  '110114009000': [504696.22004033107, 320877.1437164354],
  '110106014000': [489838.5758244457, 296404.28921397653],
  '110105037000': [513254.52650286054, 320657.174124047],
  '110109007000': [475792.44354831957, 309490.5667474699],
  '110117112000': [554132.5954486815, 343067.3269528514],
  '110109104000': [479546.6473358168, 315925.5468521315],
  '110113101000': [515103.5946094489, 332174.10352454043],
  '110114003000': [485170.50766008307, 335111.7777463427],
  '110117106000': [570905.5162077112, 328383.8563068466],
  '110113110000': [548969.6154722997, 332074.2879360123],
  '110111001000': [469136.6159615177, 282007.3321477159],
  '110112209000': [530982.22672077, 281299.7361139488],
  '110108001000': [493430.3555499703, 304364.43840186653],
  '110101001000': [504162.41870076687, 305000.4993149445],
  '110101004000': [504129.04163179465, 308638.1071916347],
  '110113108000': [539833.8299732441, 321667.5952105827],
  '110105035000': [520793.3715280057, 304329.43912453105],
  '110114104000': [480614.9386508961, 330633.53823708004],
  '110116005000': [522944.19314561883, 345820.76577959995],
  '110107003000': [486669.29063890286, 304772.3881309896],
  '110116103000': [528713.3817902112, 345336.94765624596],
  '110114113000': [497774.56125002657, 332644.6380783631],
  '110105023000': [512629.4595622422, 312018.87861484376],
  '110107010000': [482071.277075861, 311049.17997315805],
  '110114001000': [490276.89432259224, 339717.9776196471],
  '110113009000': [521336.5073598073, 334049.368012857],
  '110106009000': [494243.083137057, 298695.9727065441],
  '110111006000': [467155.08511057287, 284332.8108463831],
  '110105024000': [507815.14663851226, 311900.0608935114],
  '110105039000': [517113.6620611888, 310926.11382847297],
  '110108030000': [486953.5182973643, 327957.5619200216],
  '110107005000': [485712.25557989406, 308764.8105797232],
  '110108017000': [497526.89803640684, 319134.576942252],
  '110117108000': [555227.699603034, 328272.16991563485],
  '110108003000': [496422.9393915664, 304054.9956348131],
  '110105005000': [507955.52416830906, 309735.28518671263],
  '110105007000': [505625.88352007134, 311056.5171468797],
  '110108024000': [500881.769229996, 319375.03991841926],
  '110113115000': [515518.803450352, 342475.67641993257],
  '110108019000': [499336.52297688386, 319182.9066416393],
  '110111012000': [479453.4670600253, 285410.4939263555],
  '110118103000': [535791.130728912, 353583.37092673365],
  '110119108000': [473904.70228293235, 369381.4000193123],
  '110108021000': [490672.76278582553, 306389.4317011025],
  '110111005000': [466442.3564497042, 288497.6728585696],
  '110106005000': [502146.88061724557, 292724.19764301594],
  '110112004000': [528303.9473563032, 302137.25192074914],
  '110105030000': [512475.3304100818, 308831.72355209163],
  '110113013000': [523846.36913562776, 327128.37272587797],
  '110107009000': [480887.67680202716, 307476.4499457548],
  '110113008000': [521127.6859890912, 328826.1061294333],
  '110108010000': [499824.2157298478, 314678.76562541904],
  '110102020000': [498297.4846776087, 302042.4287781743],
  '110105040000': [520577.2622342418, 299362.1255198095],
  '110108022000': [495453.40323601064, 318626.6170288061],
  '110105041000': [517785.3185998031, 299678.0087998172],
  '110108025000': [493808.0436871763, 309780.4641145059],
  '110105003000': [509046.2453825458, 305755.07257084985],
  '110117111000': [559360.9193132261, 331837.411526696],
  '110113105000': [535114.141310533, 324405.13250940363],
  '110111209000': [455824.1166923545, 289434.0383736641],
  '110109006000': [478838.70207801403, 303463.71193139604],
  '110117005000': [555318.7163213013, 322195.6997694201],
  '110113004000': [514879.06196459086, 326975.83762913995],
  '110105031000': [502787.42419829784, 316657.8315837705],
  '110106008000': [492074.9606685185, 300880.65813784045],
  '110102010000': [502115.5315313822, 310254.2632866983],
  '110105400000': [520177.01539762743, 322932.09969595954],
  '110108004000': [496837.3063156773, 306441.7248518781],
  '110117002000': [565515.1973803494, 332703.3756923144],
  '110112003000': [524113.4217082117, 303746.8290275365],
  '110105001000': [508476.428092703, 304571.5718222392],
  '110101009000': [507006.4832534559, 307997.86974222807],
  '110101015000': [505811.9605217524, 301867.9897949173],
  '110112006000': [525498.990751467, 300517.3298317118],
  '110117003000': [563026.4811245122, 329310.7695243162],
  '110119002000': [468827.33103272476, 367062.5661416609],
  '110119109000': [470763.2331357098, 361374.9092840666],
  '110118100000': [540275.9779609514, 359052.7357971813],
  '110105025000': [505683.7497142433, 315054.26528646884],
  '110102012000': [502350.8434162727, 307525.3613939251],
  '110118003000': [543529.0114089345, 358783.0202952699],
  '110113005000': [520263.0704281391, 320532.79819236574],
  '110108016000': [486313.90055084665, 314528.20937844657],
  '110101016000': [504469.17001648963, 301650.8912047653],
  '110105016000': [509247.27446316753, 303235.9121375901],
  '110105004000': [508222.8055345347, 307659.8425754612],
  '110106013000': [506537.7816966306, 299738.32264101907],
  '110111105000': [487566.6393744757, 285885.8425744706],
  '110108023000': [491177.08332959784, 314382.3193982663],
  '110108005000': [494402.818693923, 307063.51719393017],
  '110118002000': [539794.8666136034, 356067.2094929331],
  '110105018000': [508908.5470939367, 300936.7065560554],
  '110106003000': [502446.2324727346, 298711.5917476293],
  '110109002000': [477682.6280329804, 309365.9387995905],
  '110102014000': [503042.8280213854, 301543.2260922077],
  '110113001000': [525103.9401192991, 329243.73495403025],
  '110105011000': [511675.2181224047, 312786.99854027294],
  '110113011000': [515649.0896079006, 323570.4127400704],
  '110111112000': [473627.33357360464, 291584.7845511798],
  '110105034000': [517887.43875160144, 304840.80810822034],
  '110108013000': [493120.61215475755, 315548.32947669155],
  '110105014000': [511460.3658139517, 306564.4322683044],
  '110107011000': [487955.18174155994, 302694.9102101336],
  '110116001000': [523733.91203700705, 351598.31444804015],
  '110105042000': [514933.5838616314, 301010.0070590912],
  '110113012000': [525766.2019126092, 333677.91349819436],
  '110106007000': [506678.0548464675, 298506.41853463906],
  '110106006000': [505018.7013093765, 292683.8181829585],
  '110114005000': [486123.6706037745, 339833.60876232333],
  '110111007000': [474731.94932197046, 282647.31794813194],
  '110112001000': [527516.4917791171, 304192.9080035489],
  '110111011000': [482872.0492223961, 286171.99847839866],
  '110105012000': [510041.1967416892, 308728.19101028703],
  '110113010000': [526652.564521391, 326336.76750705106],
  '110107006000': [483305.2422570341, 307316.75018166995],
  '110101007000': [505897.06990603806, 305917.35152282275],
  '110108012000': [495431.20106138143, 311844.84188396804],
  '110108002000': [492159.13082009513, 305091.24812745827],
  '110108018000': [500468.2668781288, 312312.6023801361],
  '110105017000': [509631.157887053, 302134.9966589206],
  '110102001000': [502277.05549215793, 304828.8975485728],
  '110101011000': [504040.7310633861, 303232.7962815322],
  '110102015000': [501918.55499900744, 303011.0576579425],
  '110108008000': [500058.8921457287, 310335.6259003153],
  '110102003000': [500646.2428164049, 307529.0082418961],
  '110107001000': [490065.9479826342, 303683.4410672663],
  '110102019000': [500422.1816851365, 301016.1975771206],
  '110119003000': [466821.0966268377, 366551.01062768826],
  '110105019000': [514050.7878235565, 299006.24280286056],
  '110113007000': [524813.7390186043, 339782.69444531907],
  '110119001000': [469007.07323578635, 364177.06338049035],
  '110108007000': [498218.34953353, 309676.7005750394],
  '110113106000': [532282.3177751254, 331238.0414187959],
  '110118001000': [542087.5483399306, 356134.9918182498],
  '110105015000': [511918.9276939309, 305471.9163356149],
  '110102011000': [500696.70466334734, 304917.9568162577],
  '110101002000': [504301.33308448724, 306826.72276902164],
  '110108015000': [496012.0533767363, 313900.69167722686],
  '110115110000': [505090.34766880516, 275984.0040360215],
  '110102007000': [499024.55705763405, 304560.06639294315],
  '110107002000': [489375.9976928669, 305054.49987146613],
  '110109003000': [475068.0671461585, 307677.82273582],
  '110106015000': [501134.4213743432, 297091.4971054875],
  '110105022000': [514850.9859602256, 304329.1709105677],
  '110105021000': [511610.7519515415, 301720.39758809214],
  '110109001000': [478218.497932442, 307522.9833458429],
  '110105002000': [507282.87489953806, 305918.43209269305],
  '110102016000': [502006.53981312923, 301365.77191563504],
  '110112005000': [525993.6013400909, 307268.0189345089],
  '110108020000': [493078.3560346437, 318392.632165454],
  '110108006000': [496063.2493296811, 309277.1475772357],
  '110115007000': [501843.2056028492, 288896.9082444795],
  '110115003000': [497358.33895959234, 287090.0091585876],
  '110115108000': [495231.82302080403, 271054.76409171463],
  '110106016000': [503733.7712752984, 294809.50401527947],
  '110115106000': [505208.6922412846, 265385.7634901705],
  '110108014000': [497414.70581060485, 315144.408317939],
  '110105032000': [507251.0966508343, 318339.7115121962],
  '110106012000': [479217.1986926039, 298767.7377129346],
  '110114116000': [506710.4868414377, 340664.4531279188],
  '110119100000': [465833.02246209094, 367315.6806104175],
  '110101017000': [503767.89290792716, 299908.4716001386],
  '110117001000': [564057.6039617959, 330410.7507955524],
  '110105010000': [505367.65004899347, 312724.2287712841],
  '110102017000': [500415.5246642171, 303011.89465366094],
  '110112002000': [526285.6296451895, 305408.9442903437],
  '110112114000': [521655.29404002195, 293990.4618257821],
  '110115004000': [510415.7807115822, 290722.316212749],
  '110105008000': [503493.3482314769, 311284.1873490456],
  '110101006000': [505872.80262817565, 306836.61801481986],
  '110115005000': [492946.8710331811, 287316.1966553963],
  '110115002000': [496542.2246231987, 282748.65344669914],
  '110115001000': [495893.4947249923, 285069.76459242206],
  '110102009000': [498970.2750405023, 307190.13594843616],
  '110101014000': [506838.5543633023, 301669.30811014527],
  '110106002000': [497443.45706673665, 300438.16640312766],
  '110106001000': [500504.5252593251, 299507.27296412986],
  '110114119000': [488380.72865367314, 349079.9490654935],
  '110115107000': [498381.09117065405, 259911.2784872594],
  '110115105000': [512315.94515677, 272424.7824302965],
  '110115104000': [526392.449129063, 274560.4870203633],
  '110116002000': [523500.615289369, 349762.1278869764],
  '110101005000': [505833.7569941212, 308264.5775506729],
  '110101008000': [505963.4268619687, 304636.0114827781],
  '110105006000': [506962.1222991988, 310497.4917006031],
  '110106004000': [504147.614781129, 297213.8339669295],
  '110115004000': [514016.4044629191, 294937.664704598],
  '110106005000': [503379.826432432, 295839.94211005175],
  '110115012000': [513465.90861325123, 291929.7887913707],
  '110108011000': [497631.7779963388, 312446.3978432828],
  '110115006000': [506726.1740496153, 291836.1079193983],
  '110105009000': [503325.7577655437, 313052.69440935383],
  '110105038000': [512536.23239527096, 317422.78589296667],
  '110105043000': [510076.42604960554, 315465.00943246123],
  '110114007000': [502244.6888850171, 323167.38512893836],
  '110114120000': [500075.9911560025, 350451.1437198917],
  '110111002000': [473036.42175455455, 286329.82927612506],
  '110109005000': [468247.99806374364, 309209.20538086275],
  '110101010000': [504468.6276662463, 309954.40285398206],
  '110112109000': [521311.59234541946, 286112.1832023604],
  '110106010000': [495996.6543256098, 295127.4813233793],
  '110115011000': [497212.5568931089, 288882.6561302557],
  '110105013000': [509480.59812080394, 306714.53600706265],
  '110115103000': [512404.21690499474, 280908.6768068352],
  '110106011000': [483708.9519222186, 297882.06656580983],
  '110106008000': [493557.56930572074, 300372.9550096928],
  '110107004000': [484277.3864696434, 304375.5213206208],
  '110111004000': [464335.23370737134, 286883.16573895514],
  '110113002000': [526458.6888983905, 328809.71048278804],
  '110105028000': [511897.8059097307, 297532.64211169834],
  '110101003000': [504231.6928225657, 307735.1831052503],
  '110102018000': [500411.5901964463, 302097.0284865985],
  '110102013000': [502898.0259116833, 303063.44599939807],
  '110115010000': [497625.31076481746, 279555.2557057153],
  '110115009000': [500650.45895559853, 286546.72486786486],
  '110115008000': [508859.92619788385, 287313.69860893325],
  '110115013000': [512936.9547344391, 287754.97393811034],
  '110115109000': [491665.55628960504, 278057.3631374347],
  '110115111000': [520943.4807913811, 278678.6499476553],
  '110105027000': [509046.9064909454, 295780.04091136163],
  '110113003000': [527364.4536292567, 325431.5665245152],
  '110114013000': [494480.3063612125, 325683.64788960986],
  '110114011000': [496881.35860206233, 322470.1665401081],
  '110114012000': [497901.8359745743, 323525.63666733884]
}
var shi_centers = {
  //  '110000': [527912.0425075205, 321624.2786746893],
  '110000': [560732.86379183, 358939.1640053821]
}

var regionCenters = {
  0: shi_centers,
  1: qx_centers,
  2: xz_centers
}
// key为数据库和前端全局code，value为使用的2016年行政区划layer中的code
var checkCodeList = {
  '110119203000': '110119214000',
  '110119200000': '110119207000',
  '110119202000': '110119210000',
  '110119201000': '110119209000',
  '110108029000': '110108104000',
  '110108026000': '110108101000',
  '110108027000': '110108102000',
  '110108028000': '110108103000',
  '110111008000': '110111010000',
  '110109007000': '110109103000',
  '110108030000': '110108105000',
  '110109006000': '110109102000',
  '110113106000': '110113006000',
  '110115012000': ' 110115012000',
  '110105043000': '110105044000',
  '110115013000': ' 110115013000',
  '110114013000': '110114011000',
  '110114011000': '110114012000',
  '110114012000': '110114013000'
}
function unique (arr) {
  if (!Array.isArray(arr)) {
    console.log('type error!')
    return
  }
  var arrry = []
  var obj = {}
  for (var i = 0; i < arr.length; i++) {
    if (!obj[arr[i]]) {
      arrry.push(arr[i])
      obj[arr[i]] = 1
    } else {
      obj[arr[i]]++
    }
  }
  return arrry
}
class MapUtils {
  // 更新密云和延庆区以及其乡镇街道因新老版本行政区划数据造成代码不一致问题
  static modifyErrorCode (regionCode, type) {
    let code_keys = Object.keys(checkCodeList)
    let code_values = Object.values(checkCodeList)
    if (type == 'current') {
      if (regionCode.includes('110118')) {
        regionCode = regionCode.replace('110118', '110228')
      }
      if (regionCode.includes('110119')) {
        regionCode = regionCode.replace('110119', '110229')
      }
    } else if (type == 'toGlobal') { // 查询后台数据，将regionCode更新为全局的代码以及数据库中统一使用的最新代码
      if (regionCode.length == 9) {
        if (regionCode == '110114011') {
          regionCode = '110114013000'
          return regionCode
        } else if (regionCode == '110114012') {
          regionCode = '110114011000'
          return regionCode
        } else if (regionCode == '110114013') {
          regionCode = '110114012000'
          return regionCode
        } else {
          regionCode = regionCode + '000'
        }
      }
      if (regionCode.includes('110228') || regionCode.includes('110229')) {
        if (regionCode.includes('110228')) {
          regionCode = regionCode.replace('110228', '110118')
        }
        if (regionCode.includes('110229')) {
          regionCode = regionCode.replace('110229', '110119')
        }
        if (code_values.includes(regionCode)) {
          let index = code_values.indexOf(regionCode)
          regionCode = code_keys[index]
        }
      } else if (code_values.includes(regionCode)) {
        let index = code_values.indexOf(regionCode)
        regionCode = code_keys[index]
      }
    } else if (type == 'toLayer') { // 查询地图图层，将regionCode更新为地图中的代码（2016旧代码）
      if (regionCode == '110114011000') {
        regionCode = '110114012'
        return regionCode
      } else if (regionCode == '110114012000') {
        regionCode = '110114013'
        return regionCode
      } else if (regionCode == '110114013000') {
        regionCode = '110114011'
        return regionCode
      }
      if (regionCode.includes('110118') || regionCode.includes('110119')) {
        if (code_keys.includes(regionCode)) {
          regionCode = checkCodeList[regionCode]
        }
        if (regionCode.includes('110118')) {
          regionCode = regionCode.replace('110118', '110228')
        }
        if (regionCode.includes('110119')) {
          regionCode = regionCode.replace('110119', '110229')
        }
      } else if (code_keys.includes(regionCode)) {
        regionCode = checkCodeList[regionCode]
      }
    }
    return regionCode
  }
  static async createGraphicsLayer (view, regionLevel, regionCode, mapData, fillColor) {
    const [GraphicsLayer, Graphic, Point, SpatialReference, IdentifyTask, IdentifyParameters] = await loadEsriModule([
      'esri/layers/GraphicsLayer',
      'esri/Graphic',
      'esri/geometry/Point',
      'esri/geometry/SpatialReference',
      'esri/tasks/IdentifyTask',
      'esri/tasks/support/IdentifyParameters'
    ])

    if (mapData) {
      if (mapData.length > 0) {
        // 是否绘制气泡图
        let isContinue = false// regionCode == '110000' ? true : !!((regionCode.length == 6 && mapData[0].regioncode.length == 12))
        if (regionCode == '110000') {
          isContinue = true
        } else if (regionCode && regionCode.length == 6) {
          for (var i = 0; i < mapData.length; i++) {
            let curCode = mapData[i].regioncode
            if (curCode && curCode.length == 12) {
              isContinue = true
              break
            }
          }
        } else {
          isContinue = false
        }
        if (isContinue) {
          let mapNewData = this.joinDataWithXY(regionLevel, regionCode, mapData)
          view.graphics.removeAll()// 清除上一次点击目标
          view.popup.visible = false
          var graphicsLayer = new GraphicsLayer({
            id: 'layer-bubble'
          })
          let sr = new SpatialReference({
            wkt: env.getInitialExtent().wkt // '"PROJCS["Krassovsky_1942_Transverse_Mercator",GEOGCS["GCS_Krassovsky_1942",DATUM["D_unknown",SPHEROID["krass",6378245.0,298.3]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["false_easting",500000.0],PARAMETER["false_northing",300000.0],PARAMETER["central_meridian",116.350253],PARAMETER["scale_factor",1.0],PARAMETER["latitude_of_origin",39.865767],UNIT["Meter",1.0]]"'
          })
          var color = colorRgba(fillColor)
          let graphicParam = mapNewData
          for (let i = 0; i < graphicParam.length; i++) {
            if (graphicParam[i].value == 0) continue
            let point = new Point({
              x: graphicParam[i].x,
              y: graphicParam[i].y,
              spatialReference: view.extent ? view.extent.spatialReference : sr
            })
            let graphic_circle = new Graphic({
              // geometry: new Circle({
              //   center:point,
              //   // numberOfPoints: 100,
              //   // radius: graphiclayerParam[i].area/20,
              //   // radiusUnit: 'meters'
              // }),
              geometry: point,
              attributes: graphicParam[i],
              symbol: {
                type: 'simple-marker', // autocasts as new SimpleFillSymbol()
                color: color, // [255,255,0,0.5],
                // style: "solid",
                size: graphicParam[i].size + 'px',
                outline: {
                  width: 0,
                  color: [255, 255, 255, 0]
                }
              }
            })
            let textSymbol = {
              type: 'text',
              color: '#fff', //
              text: this.dataFormatDisplay(regionLevel, graphicParam[i].value), // graphicParam[i].value.toFixed(regionLevel == 1 ? (Math.abs(graphicParam[i].value) > 1 ? 0 : 2) : (graphicParam[i].value.toString().split('.')[1] ? 2 : 0)).toString(), // esri-icon-map-pin
              verticalAlignment: 'middle',
              font: {
                size: 13,
                weight: 'bold',
                family: 'sans-serif'
              }
            }
            let graphic_label = new Graphic({
              geometry: point,
              symbol: textSymbol// graphicParam[i].size != 10 ? textSymbol : null// (graphicParam[i].size!=10)?((graphicParam[i].value>=1?textSymbol:null)):null
            })
            graphicsLayer.add(graphic_circle)
            graphicsLayer.add(graphic_label)
          }
          view.map.add(graphicsLayer)

          return graphicsLayer
        }
      }
    }
  }

  // level为1时，若value大于1，不保留小数，若大于0小于1，则保留两位，若等于0，则为null
  // level大于1时，若value为有小数部分，保留两位小数，若无小数部分，则不保留，若等于0，则为null
  static dataFormatDisplay (regionLevel, value) {
    if (regionLevel == 1) {
      let v = Math.abs(value)
      if (v >= 1) {
        return value.toFixed(0).toString()
      } else if (v > 0) {
        return value.toFixed(2).toString()
      }
      // else if(v == 0){
      //   return '0'
      // }
    } else {
      // if(value == 0) return '0'
      let v = value.toString().split('.')[1]
      if (v) {
        return value.toFixed(2).toString()
      } else {
        return value.toFixed(0).toString()
      }
    }
    // graphicParam[i].value.toFixed(regionLevel == 1 ? (Math.abs(graphicParam[i].value) > 1 ? 0 : 2) : (graphicParam[i].value.toString().split('.')[1] ? 2 : 0)).toString()
  }
  static joinDataWithXY (spatialUnit, regionCode, mapData) {
    // this.initRegionFeatures(spatialUnit, regionCode)
    let regionCenterDict = regionCenters[spatialUnit]

    let values = Sort(mapData)
    let naturalBreaks = this.getJenksBreaks(values, 7)
    let size_list = [10, 40, 50, 60, 80, 90, 100, 110]// [120,100,80,20,10]//
    let div = spatialUnit == 1 ? 1 : 2
    if (regionCenterDict) {
      for (let i = 0; i < mapData.length; i++) {
        let code = mapData[i].regioncode
        let value = Math.abs(mapData[i].value)
        if (regionCenterDict[code] == undefined) {
          continue
        }
        mapData[i].x = regionCenterDict[code][0]
        mapData[i].y = regionCenterDict[code][1]

        for (let j = 0; j < naturalBreaks.length - 1; j++) {
          if (value >= naturalBreaks[j] && value < naturalBreaks[j + 1]) {
            mapData[i].size = size_list[j] / div
            break
          }
        }
        if (value < naturalBreaks[0]) {
          mapData[i].size = size_list[0] / div
        }
        if (value >= naturalBreaks[naturalBreaks.length - 1]) {
          mapData[i].size = size_list[naturalBreaks.length] / div
        }
      }
    }
    return mapData
  }
  static async initRegionFeatures (spatialUnit, regionCode) {
    // 持有乡镇及区县的Features
    let self = this

    const [QueryTask, Query] = await loadEsriModule([
      'esri/tasks/QueryTask',
      'esri/tasks/support/Query'
    ])
    let task
    spatialUnit = 2
    if (spatialUnit == 1) {
      task = new QueryTask({
        url: env.getMapServer().qxUrl
      })
    } else if (spatialUnit == 2) {
      task = new QueryTask({
        url: env.getMapServer().xzUrl
      })
    } else if (spatialUnit == 3) {
      task = new QueryTask({
        url: env.getMapServer().xzUrl
      })
    }

    let query = new Query({
      where: '1=1', // spatialUnit==1?'1=1':((spatialUnit==2?"qxcode = '":"xzcode = '")+regionCode+"'"),
      outFields: ['*'],
      returnGeometry: true
    })

    task.execute(query).then(function (result) {
      let features = result.features
      let codes = []
      let centers = []
      // var regionCenters = {};
      for (let i = 0; i < features.length; i++) {
        codes.push(features[i].attributes['code'])
        centers.push([features[i].geometry.centroid.x, features[i].geometry.centroid.y])
      }
      for (var i = 0; i < codes.length; i++) {
        let regionCenter = {}
        regionCenter.name = codes[i]
        regionCenter.value = centers[i]
        regionCenters.push(regionCenter)
        // console.log("'" + codes[i] + "':[" + centers[i][0] + ',' + centers[i][1] + '],')
      }
    })
    return regionCenters
  }
  // 添加Featurelayer
  static async addFeatureLayer (view, source, popupTemplate, flag) {
    const [FeatureLayer, Field] = await loadEsriModule([
      'esri/layers/FeatureLayer',
      'esri/layers/support/Field'
    ])
    const fLayer = view.map.layers.find(lyr => {
      return lyr.id === 'layer-g'
    })
    if (fLayer) {
      // 先移除
      view.map.remove(fLayer)
    }
    let featureLayer
    if (flag == 'source') {
      featureLayer = new FeatureLayer({
        source: source,
        id: 'layer-g',
        objectIdField: 'OBJECTID',
        title: '专题地图',
        geometryType: 'polygon',
        popupEnabled: true,
        popupTemplate: popupTemplate,
        spatialReference: view.spatialReference,
        fields: [new Field({
          name: 'OBJECTID',
          alias: 'OBJECTID',
          type: 'oid'
        }), new Field({
          name: 'code',
          alias: 'code',
          type: 'string'
        }), new Field({
          name: 'name',
          alias: 'name',
          type: 'string'
        }), new Field({
          name: 'renderval',
          alias: 'renderval',
          type: 'double'
        }), new Field({
          name: 'area',
          alias: 'area',
          type: 'double'
        })],
        renderer: {
          type: 'simple',
          symbol: {
            type: 'simple-fill',
            style: 'none',
            outline: {
              type: 'simple-line', // autocasts as new SimpleLineSymbol()
              color: [6, 32, 52, 0.9],
              width: 1.0,
              style: 'solid'
            }
          }
        }
      })
    } else {
      featureLayer = new FeatureLayer({
        url: source,
        id: 'layer-g',
        title: '专题地图',
        popupTemplate: popupTemplate
      })
    }
    view.map.add(featureLayer)
    return featureLayer
  }
  // 添加拆违图层
  static async addChaiWeiLayer (view, year, popupTemplate, regionLevel, regionName) {
    const [MapImageLayer] = await loadEsriModule([
      'esri/layers/MapImageLayer'
    ])
    const fLayer = view.map.layers.find(lyr => {
      return lyr.id === 'layer-chaiwei'
    })
    // let queryRegionFieldDict = { '2017': 'town_1', '2018': 'town_1', '2019': 'town' }
    // regionName = regionName.replace('街道', '').replace('乡', '').replace('镇', '')
    // let regionField = queryRegionFieldDict[year]
    if (fLayer) {
      // 先移除
      view.map.remove(fLayer)
    }

    let imgLayer = new MapImageLayer({
      url: env.getOtherMapServer().chaiwei[year],
      id: 'layer-chaiwei',
      sublayers: [{
        id: 0,
        title: '拆违图斑',
        visible: false,
        source: {
          mapLayerId: 0
        },
        popupTemplate: popupTemplate,
        outFields: ['*'],
        visible: !(parseInt(regionLevel) <= 2),
        popupEnabled: !(parseInt(regionLevel) > 3),
        renderer: {
          type: 'simple',
          symbol: {
            type: 'simple-fill',
            // style: 'none',
            color: [255, 0, 0, 0],
            outline: {
              type: 'simple-line', // autocasts as new SimpleLineSymbol()
              color: [255, 0, 0, 1],
              width: 2,
              style: 'solid'
            }
          }
        }
      }]

    })
    // console.log(env.getOtherMapServer().chaiwei[year])
    view.map.add(imgLayer)
    // view.map.reorder(featureLayer,2)
    return imgLayer
  }
  // 添加底图
  static async addBaseLayer (view, url, regeionLevel) {
    const [TileLayer] = await loadEsriModule([
      'esri/layers/TileLayer'
    ])
    const fLayer = view.map.layers.find(lyr => {
      return lyr.id === 'layer-basemap'
    })
    if (fLayer) {
      // 先移除
      view.map.remove(fLayer)
    }

    let isDzdt = url.indexOf('DZDT') > 0 || url.indexOf('dzdt') > 0
    let baseLayer = new TileLayer({
      url: url,
      id: 'layer-basemap',
      visible: regeionLevel >= 2
      // maxScale: 500,
      // minScale: isDzdt?2000000:1000000
    })
    view.map.add(baseLayer, 0)
    return baseLayer
  }
  // 获取地图服务url信息
  static getInfoFromMapUrl (url) {
    let urls = url.split('/')
    let formatUrl = url
    let subLayerIndex
    if (urls[urls.length - 1].toUpperCase() == 'MAPSERVER' || urls.includes('API') || urls.includes('api')) {
      formatUrl = url
    } else {
      let lastIndex = url.lastIndexOf('/')
      formatUrl = url.substr(0, lastIndex)
      subLayerIndex = parseInt(urls[urls.length - 1])
    }
    return [formatUrl, subLayerIndex]
  }
  // 添加各类图层
  static async addLayer (view, url, layerType, layerOpacity, labelName, popupTemplate, callback) {
    if (url) {
      let urlInfo = this.getInfoFromMapUrl(url)
      let formatUrl = urlInfo[0]
      let subLayerIndex = urlInfo[1]
      const [MapImageLayer, TileLayer, SpatialReference] = await loadEsriModule([
        'esri/layers/MapImageLayer',
        'esri/layers/TileLayer',
        'esri/geometry/SpatialReference'
      ])
      let layer_label = labelName.split('_')[1]
      let shpLayer
      let imgLayer
      let regionLayer
      let renderer = {
        type: 'simple',
        symbol: {
          type: 'simple-fill',
          color: [11, 17, 41, 0],
          outline: {
            width: 1,
            color: '#fff'
          }
        }
      }
      regionLayer = view.map.layers.find(lyr => {
        return lyr.id === 'layer-boundary'
      })
      // 判断是否存在行政区边界，如果没有，则说明是首次进入图斑页，默认添加村界，否则是进入后切换不同图层
      if (!regionLayer) {
        let regionUrlInfo = this.getInfoFromMapUrl(env.getMapServer().cunUrl)
        let regionUrl = regionUrlInfo[0]
        let subLayerId = regionUrlInfo[1]
        // let regionUrl = env.getMapServer().cunUrl.split('MapServer')[0]+'MapServer'
        regionLayer = new MapImageLayer({
          url: regionUrl,
          id: 'layer-boundary',
          title: '村界',
          sublayers: [{
            id: 0,
            visible: subLayerId == 0,
            renderer: subLayerId == 0 ? renderer : null
          },
          {
            id: 1,
            visible: subLayerId == 1,
            renderer: subLayerId == 1 ? renderer : null
          },
          {
            id: 2,
            visible: subLayerId == 2,
            renderer: subLayerId == 2 ? renderer : null
          },
          {
            id: 3,
            visible: subLayerId == 3,
            renderer: subLayerId == 3 ? renderer : null
          },
          {
            id: 4,
            visible: subLayerId == 4,
            renderer: subLayerId == 4 ? renderer : null
          },
          {
            id: 5,
            visible: subLayerId == 5,
            renderer: subLayerId == 5 ? renderer : null
          }]
        })
        view.map.add(regionLayer, 4) // adds the layer to the map
      } else {
        if (layerType == 'boundary') {
          view.map.remove(regionLayer)
        }
      }

      let regionLabels = ['sj', 'qj', 'xzj', 'cj']
      if (!regionLabels.includes(layer_label)) {
        renderer = null
      }
      if (layerType == 'img') {
        imgLayer = view.map.layers.find(lyr => {
          return lyr.id === 'layer-img'
        })
        if (imgLayer) {
          // 先移除
          view.map.remove(imgLayer)
        }
      } else if (layerType == 'shp') {
        shpLayer = view.map.layers.find(lyr => {
          return lyr.id === 'layer-shp'
        })
        if (shpLayer) {
          // 先移除
          view.map.remove(shpLayer)
        }
      }
      let layer
      let json_url = formatUrl + '?f=json'
      Axios.get(json_url).then(res => {
        if (res.data['tileInfo'] && layer_label != 'cskfbj') {
          layer = new TileLayer({
            url: formatUrl,
            id: 'layer-' + layerType,
            visible: true,
            opacity: layerOpacity
          //  spatialReference: new SpatialReference({ wkt: env.getInitialExtent().wkt })
          })
          // tilelayer sublayers是只读的，但其弹窗属性是可以更改的，目前只能通过load()来设置
          layer.load().then(function (layerV) {
            var sublayer = layerV.findSublayerById(subLayerIndex || 0)
            sublayer.popupTemplate = popupTemplate
          })
        } else {
          layer = new MapImageLayer({
            url: formatUrl,
            id: 'layer-' + layerType,
            title: '专题地图',
            opacity: layerType == 'boundary' ? 1 : layerOpacity, // layerType == 'img' ? 1 : 0.4,
            sublayers: [{
              id: 0,
              visible: true,
              popupTemplate: popupTemplate,
              renderer: renderer
            },
            {
              id: 1,
              visible: false,
              popupTemplate: popupTemplate,
              renderer: renderer
            },
            {
              id: 2,
              visible: false,
              popupTemplate: popupTemplate,
              renderer: renderer
            },
            {
              id: 3,
              visible: false,
              popupTemplate: popupTemplate,
              renderer: renderer
            },
            {
              id: 4,
              visible: false,
              popupTemplate: popupTemplate,
              renderer: renderer
            },
            {
              id: 5,
              visible: false,
              popupTemplate: popupTemplate,
              renderer: renderer
            }]
          })
        }

        if (layerType == 'img') {
          view.map.add(layer, 2)
          // view.map.reorder(layer, 1)
        } else if (layerType == 'shp') {
          view.map.add(layer, 3)
        } else {
          view.map.add(layer, 4)
        }
        if (callback) callback(layer, subLayerIndex)
      })
    }
  }

  static async renderFeatureLayer (view, featureLayer, renderData, classBreaks, legendData) {
    const classBreakRGBColors = [
      [213, 204, 199, 1], // 数值为0对应的颜色
      [84, 173, 223, 1],
      [85, 190, 182, 1],
      [164, 199, 68, 1],
      [238, 213, 48, 1],
      [249, 54, 20, 1]
    ]
    const noLegendHEXColor = '#6E6E6E'
    const classBreakHEXColors = [
      '#D4CDC7',
      '#56B3EC',
      '#56BDB9',
      '#A7C746',
      '#EDD430',
      '#FF331a'
    ]
    legendData[0].items = []
    let renderer = {
      type: 'class-breaks',
      field: 'renderval',
      defaultSymbol: {
        type: 'simple-fill',
        style: 'none',
        outline: {
          type: 'simple-line', // autocasts as new SimpleLineSymbol()
          color: [6, 32, 52, 0.9],
          width: 0.6,
          style: 'solid'
        }
      },
      classBreakInfos: []
    }
    if (renderData && renderData.length > 0) {
      // var isFloat = false;
      // 此处进行分级渲染
      let isHavaZero = false
      let gs = []
      for (var i = 0; i < featureLayer.source.items.length; i++) {
        var g = featureLayer.source.items[i]
        var v = getRenderValByRegionCode(renderData, g.attributes['code'])
        if (v == 0) isHavaZero = true
        g.attributes['renderval'] = v
        gs.push(g)
      }
      let start = new Date().getTime()
      await featureLayer.applyEdits({ updateFeatures: gs })
      let end = new Date().getTime()
      // console.log('renderFeatureLayer applyEdits cost time:' + end - start)
      // 设置分级渲染区间
      if (isHavaZero) {
        renderer.classBreakInfos.push({
          minValue: 0,
          maxValue: 0,
          label: '0',
          symbol: {
            type: 'simple-fill',
            color: classBreakRGBColors[0],
            outline: {
              type: 'simple-line', // autocasts as new SimpleLineSymbol()
              color: [6, 32, 52, 0.9],
              width: 0.6,
              style: 'solid'
            },
            style: 'solid'
          }
        })
        legendData[0].items.push({
          label: '0',
          alias: aliasLevels[0],
          color: classBreakHEXColors[0],
          visible: true
        })
      }
      // var digits = isFloat ? 2 : 0;
      for (let j = 0; j < classBreaks.length; j++) {
        if (classBreaks[j][0] == 0 && classBreaks[j][1] == 0) continue
        renderer.classBreakInfos.push({
          minValue: classBreaks[j][0],
          maxValue: classBreaks[j][1],
          label: classBreaks[j][0] + '-' + classBreaks[j][1],
          symbol: {
            type: 'simple-fill',
            color: classBreakRGBColors[j + 1],
            outline: {
              type: 'simple-line', // autocasts as new SimpleLineSymbol()
              color: [6, 32, 52, 0.9],
              width: 0.6,
              style: 'solid'
            },
            style: 'solid'
          }
        })
        legendData[0].items.push({
          label: classBreaks[j][0] + '-' + classBreaks[j][1],
          alias: aliasLevels[j],
          color: classBreakHEXColors[j + 1],
          visible: true
        })
      }
      featureLayer.renderer = renderer
    } else {
      // 无数据时，更新图例
      legendData[0].items.push({
        label: '暂无数据',
        alias: aliasLevels[0],
        color: noLegendHEXColor,
        visible: true
      })
      featureLayer.renderer = renderer
    }
  }

  static removeLayerByLayerIds (view, layerId) {
    const fLayer = view.map.layers.find(lyr => {
      return lyr.id === layerId
    })
    if (fLayer) {
      view.map.layers.remove(fLayer)
    }
  }

  static getSelectionSymbol () {
    return {
      type: 'simple-line',
      color: [176, 255, 255, 1],
      width: 2,
      style: 'solid'
    }
  }

  static queryFeatures (view, layerId, regionCode) {
    // 1、查找图层
    const fLayer = view.map.layers.find(lyr => {
      return lyr.id === layerId// 'layer-g'
    })
    // 2、查找Feature
    let query = fLayer.createQuery()
    query.where = "code = '" + regionCode + "'"
    return fLayer.queryFeatures(query)
  }

  static queryFeatureByObjectId (view, objectId) {
    // 1、查找图层
    const fLayer = view.map.layers.find(lyr => {
      return lyr.id === 'layer-g'
    })
    // 2、查找Feature
    let query = fLayer.createQuery()
    query.where = 'OBJECTID = ' + objectId + ''
    return fLayer.queryFeatures(query)
  }

  static async getFieldUniqueValues (subLayer, chartClick) {
    let query = subLayer.createQuery()
    let results = []
    try {
      query.where = "dlmc ='" + chartClick + "'"
      query.outFields = ['zlmc']
      query.returnGeometry = false
      let qr = await subLayer.queryFeatures(query)
      for (let i = 0; i < qr.features.length; i++) {
        let val = qr.features[i].attributes['zlmc']
        if (!contains(results, val)) {
          results.push(val)
        }
      }
    } catch (err) {
      console.log(err)
    } finally {
      return results
    }
  }

  static async renderSubLayer (subLayer, chartClick, legendData) {
    // 1、设置图层=chartClick的图层定义
    let layerDefinition = " dlmc = '" + chartClick + "'"
    subLayer.definitionExpression = layerDefinition
    // 2、根据按照zlmc进行唯一值渲染
    let uniqueValues = await this.getFieldUniqueValues(subLayer, chartClick)
    if (uniqueValues.length == 0) return false
    let uniqueValueInfos = []
    for (let i = 0; i < uniqueValues.length; i++) {
      let fillColor = getRandomColor()
      uniqueValueInfos.push({
        value: uniqueValues[i],
        symbol: {
          type: 'simple-fill',
          color: fillColor,
          outline: {
            type: 'simple-line', // autocasts as new SimpleLineSymbol()
            color: [6, 32, 52, 0.9],
            width: 0.6,
            style: 'solid'
          },
          style: 'solid'
        }
      })
      // legendData[0].items.push({
      //     label: uniqueValues[i],
      //     alias: uniqueValues[i],
      //     color: fillColor,
      //     visible: true
      // });
    }
    let renderer = {
      type: 'unique-value',
      field: 'zlmc',
      defaultSymbol: { type: 'simple-fill' }, // autocasts as new SimpleFillSymbol()
      uniqueValueInfos: uniqueValueInfos
    }
    subLayer.renderer = renderer
  }
  // 展示拆违属性信息
  static displayFieldsInfo (year, attributes) {
    let newYear = year.toString()
    var baseInfodata = []
    if (newYear == '2017' || newYear == '2016') {
      baseInfodata = [
        { name: '台账号', content: attributes['id_1'] },
        { name: '行政区', content: attributes['county_1'] },
        { name: '街道乡镇', content: attributes['town_1'] },
        { name: '社区行政村', content: attributes['village'] },
        { name: '地址', content: attributes['itplace'] },
        { name: '腾退用地面积', content: attributes['areause'] + '平方米' },
        { name: '拆违建筑面积', content: attributes['areabuil_1'] + '平方米' },
        { name: '台账类型', content: attributes['pre3'] }

      ]
    } else if (newYear == '2018') {
      baseInfodata = [
        { name: '台账号', content: attributes['id_1'] },
        { name: '所在区', content: attributes['county_1'] },
        { name: '乡镇/街道', content: attributes['town_1'] },
        { name: '社区行政村', content: attributes['village'] },
        { name: '地址', content: attributes['itplace'] },
        { name: '腾退用地面积', content: attributes['areUse'] + '平方米' },
        { name: '拆违建筑面积', content: attributes['areBld'] + '平方米' },
        { name: '台账类型', content: attributes['台账类型'] },
        { name: '台账状态', content: attributes['台账状态'] },
        { name: '土规分类1', content: attributes['土规分类1'] },
        { name: '土规分类2', content: attributes['土规分类2'] },
        { name: '城规分类', content: attributes['城规分类'] },
        { name: '违建类型', content: attributes['illTyp'] }
      ]
    } else if (newYear >= '2019') {
      baseInfodata = [
        { name: '台账号', content: attributes['id'] },
        { name: '社区/行政村', content: attributes['village'] },
        { name: '所在区', content: attributes['county'] },
        { name: '乡镇/街道', content: attributes['town'] },
        { name: '项目名称', content: attributes['itname'] },
        { name: '占地面积', content: attributes['areause'] + '平方米' },
        { name: '建设面积', content: attributes['areabuild'] + '平方米' },
        { name: '使用性质', content: attributes['usepropert'] },
        { name: '腾地类型', content: attributes['illegaltyp'] },
        { name: '建设状态', content: attributes['buildstatu'] },
        { name: '建设时间', content: attributes['buildtime'] },
        { name: '建设主体', content: attributes['unitbuild'] },
        { name: '建设主体性质', content: attributes['unitkindbu'] },
        { name: '违法建设类型', content: attributes['typebuildk'] },
        { name: '是否留白增绿', content: attributes['isLBZL'] },
        { name: '销账时间', content: attributes['xzsj'] }
      ]
    }
    if (baseInfodata.length > 0) {
      let timestr = baseInfodata[baseInfodata.length - 1].content
      if (timestr && timestr.toString().length > 10) {
        baseInfodata[baseInfodata.length - 1].content = this.getLocalTime(timestr)
      }
    }
    return baseInfodata
  }
  // 格式化拆违时间戳，转换为常用日期
  static getLocalTime (nS) {
    return new Date(nS).toLocaleString().replace(/:\d{1,2}$/, ' ').slice(0, 9)
  }
  // 返回拆违图斑时间筛选条件
  static getTimeFilter (year, month) {
    let startTimeStr = ''
    let endTimeStr = ''
    let whereSql = ''
    if (month != '13') {
      if (month < 12) {
        if (month == 1) {
          startTimeStr = (parseInt(year) - 1).toString() + '/12'
        } else {
          startTimeStr = year.toString() + '/' + month.toString()
        }
        endTimeStr = year.toString() + '/' + (parseInt(month) + 1).toString()
      } else {
        startTimeStr = year.toString() + '/' + month.toString()
        endTimeStr = (parseInt(year) + 1).toString() + '/1'
      }
      whereSql = "xzsj >= date '" + startTimeStr + "' and xzsj < date '" + endTimeStr + "'"
    } else {
      whereSql = ''
    }
    // let startTimeStamp = (new Date(startTimeStr)).valueOf();
    // let endTimeStamp = (new Date(endTimeStr)).valueOf();
    // let whereSql = "(xzsj >='" + startTimeStamp + "' and xzsj < '" + endTimeStamp + "') or (xzsj >='" + startTimeStr + "' and xzsj < '" + endTimeStr + "')"
    return whereSql
  }
  // 空间查询（Identify）
  static async QueryTaskByGeometry (view, geometry) {
    const [IdentifyTask, IdentifyParameters] = await loadEsriModule([
      'esri/tasks/IdentifyTask',
      'esri/tasks/support/IdentifyParameters'
    ])
    let urlInfo = this.getInfoFromMapUrl(env.getMapServer().cunUrl)
    var identifyTask, params
    identifyTask = new IdentifyTask(urlInfo[0])
    params = new IdentifyParameters()
    params.tolerance = 3
    params.layerIds = [0]
    params.layerOption = 'all'
    params.width = view.width
    params.height = view.height
    params.returnGeometry = true
    params.geometry = geometry
    params.mapExtent = view.extent
    identifyTask
      .execute(params)
      .then(function (response) {
        // console.log(response)
        if (response.results.length > 0) {
          response.results.forEach(function (result) {
            let graphic = result.feature
            graphic.symbol = {
              type: 'simple-fill',
              color: [11, 17, 41, 0], // [19, 41, 55, 0],
              outline: {
                width: 2,
                color: '#fff'// [127,255,0,1],//'#0692a4',//"white",
              }
            }
            view.graphics.add(graphic)
          })
        }
      })
  }
  // 空间查询（Query）
  static async SpatialQuery (view, queryGeom) {
    const [Query, QueryTask, FeatureLayer, LabelClass] = await loadEsriModule([
      'esri/tasks/support/Query',
      'esri/tasks/QueryTask',
      'esri/layers/FeatureLayer',
      'esri/layers/support/LabelClass'
    ])

    let layerUrl = env.getMapServer().cunUrl
    let queryTask = new QueryTask({
      url: layerUrl
    })

    let query = new Query()
    // query.where ='1=1'
    query.geometry = queryGeom
    query.spatialRelationship = 'intersects'// 'contains';//default "intersects"
    query.returnGeometry = true
    query.outFields = ['*']

    queryTask.execute(query).then(function (response) {
      // console.log(response.features)
      let features = response.features
      let fields = response.fields
      const statesLabelClass = {
        labelExpressionInfo: {
          expression: '$feature.XZQMC'
        },
        symbol: {
          type: 'text',
          color: [255, 0, 0, 1],
          font: {
            size: 12
            // family: 'sans-serif'
          }
        },
        minScale: 2160000,
        maxScale: 10000
      }
      if (features.length > 0) {
        let featureLayer = new FeatureLayer({
          source: features,
          id: 'layer-cun',
          objectIdField: 'OBJECTID_1',
          title: '村界',
          geometryType: 'polygon',
          popupEnabled: false,
          spatialReference: view.spatialReference,
          labelingInfo: [ statesLabelClass ],
          fields: fields,
          renderer: {
            type: 'simple',
            symbol: {
              type: 'simple-fill',
              color: [11, 17, 41, 0],
              outline: {
                width: 2,
                color: '#fff'
              }
            }
          }
        })
        view.map.add(featureLayer)
      }
    })
  }

  static getJenksBreaks (data, numclass) {
    let numdata = data.length
    var mat1 = []
    var mat2 = []
    let st = []
    try {
      for (let j = 0; j <= numdata; j++) {
        mat1[j] = []
        mat2[j] = []
        st[j] = 0
        for (let i = 0; i <= numclass; i++) {
          mat1[j][i] = 0
          mat2[j][i] = 0
        }
      }

      for (let i = 1; i <= numclass; i++) {
        mat1[1][i] = 1
        mat2[1][i] = 0
        for (let j = 2; j <= numdata; j++) {
          mat2[j][i] = Number.MAX_VALUE
        }
      }
      let v = 0

      for (let l = 2; l <= numdata; l++) {
        let s1 = 0
        let s2 = 0
        let w = 0
        let i3 = 0
        for (let m = 1; m <= l; m++) {
          i3 = l - m + 1

          let val = data[i3 - 1]

          s2 += val * val
          s1 += val

          w++
          v = s2 - (s1 * s1) / w
          let i4 = i3 - 1
          if (i4 !== 0) {
            for (let j = 2; j <= numclass; j++) {
              if (mat2[l][j] >= (v + mat2[i4][j - 1])) {
                mat1[l][j] = i3
                mat2[l][j] = v + mat2[i4][j - 1]

              //  if (l === 200 && j === 5) alert('l=' + 200 + ',j=' + 5 + ';mat2[200][5]=' + mat1[l][j] + 'i3=' + i3)
              }
            }
          }
        }

        mat1[l][1] = 1
        mat2[l][1] = v
      }

      let k = numdata
      let kclass = []

      /* int[] kclass = new int[numclass]; */
      kclass[numclass - 1] = data[data.length - 1]
      /* kclass[numclass - 1] = (Integer) data.get(data.size() - 1); */

      for (let j = numclass; j >= 2; j--) {
        let id = parseInt(mat1[k][j]) - 2
        if (id >= 0) {
          kclass[j - 2] = data[id]
          k = parseInt(mat1[k][j] - 1)
        }
      }
      return unique(kclass)
    } catch (error) {
      console.log(error)
    }
  }
  static queryLayerViewAgeStats (layerView, countPopulation, buffer) {
    const query = layerView.layer.createQuery()
    query.outStatistics = countPopulation
    query.geometry = buffer
    query.spatialRelationship = 'intersects'
    return layerView.queryFeatures(query)
      .then(function (results) {
        const attributes = results.features[0].attributes
        let value = attributes[countPopulation[0].outStatisticFieldName]
        return value
      })
      .catch(function (error) {
        console.log(error)
      })
  }
}

export default MapUtils
